package com.example.bluetooth.ble.scanle;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Handler;

import com.example.bluetooth.ble.listener.OnScanDeviceListener;
import com.example.bluetooth.ble.listener.OnStopSelectDeviceListener;
import com.example.bluetooth.ble.service.BluetoothLeService;


/**
 * Created by HP on 2017/5/26.
 */

public class ScanLeImpl implements ScanLe {

    private static volatile ScanLeImpl mScanLe;
    private Handler mHandler;
    private OnScanDeviceListener mOnScanDeviceListener;
    private OnStopSelectDeviceListener mOnStopSelectDeviceListener;

    public void setOnStopSelectDeviceListener(OnStopSelectDeviceListener listener) {
        this.mOnStopSelectDeviceListener = listener;
    }

    public void setOnScanDeviceListener(OnScanDeviceListener listener) {
        this.mOnScanDeviceListener = listener;
    }

    public static ScanLeImpl getInstance() {
        if (null == mScanLe) {
            synchronized (ScanLeImpl.class) {
                if (null == mScanLe) {
                    mScanLe = new ScanLeImpl();
                }
            }
        }
        return mScanLe;
    }

    protected ScanLeImpl() {
        mHandler = new Handler();
    }

    private Runnable stopScanRunable = new Runnable() {
        @Override
        public void run() {
            //停止搜索
            stopLeScan();
        }
    };

    public void scanLeDevice(boolean enable) {
        if (enable) {
            mHandler.postDelayed(stopScanRunable, 30 * 1000);
            startLeScan();
        } else {
            stopLeScan();
            mHandler.removeCallbacks(stopScanRunable);
        }
    }

    public void scanLeDevice(boolean enable, int time) {
        if (enable) {
            mHandler.postDelayed(stopScanRunable, time * 1000);
            startLeScan();
        } else {
            stopLeScan();
            mHandler.removeCallbacks(stopScanRunable);
        }
    }

    @Override
    public void startLeScan() {
        BluetoothLeService.getInstance().getBluetoothAdapter().startLeScan(mLeScanCallback);
    }

    @Override
    public void stopLeScan() {
        BluetoothLeService.getInstance().getBluetoothAdapter().stopLeScan(mLeScanCallback);
        if (null != mOnStopSelectDeviceListener) {
            mHandler.removeCallbacks(stopScanRunable);
            mOnStopSelectDeviceListener.onStopSelect();
        }
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice bluetoothDevice, int rssi, byte[] bytes) {
            if (mOnScanDeviceListener != null)
                mOnScanDeviceListener.onScanDevice(bluetoothDevice, rssi);
        }
    };
}
